package com.sakura.seckill.service.impl;

import com.sakura.seckill.exception.GlobalException;
import com.sakura.seckill.pojo.User;
import com.sakura.seckill.mapper.UserMapper;
import com.sakura.seckill.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sakura.seckill.utils.CookieUtil;
import com.sakura.seckill.utils.MD5Util;
import com.sakura.seckill.utils.UUIDUtil;
import com.sakura.seckill.vo.LoginVo;
import com.sakura.seckill.vo.RespBean;
import com.sakura.seckill.vo.RespBeanEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sakura
 * @since 2022-07-26
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 登录功能实现
     * @param loginVo
     * @param request
     * @param response
     * @return
     */
    @Override
    public RespBean doLogin(LoginVo loginVo, HttpServletRequest request, HttpServletResponse response) {
        //获取手机号和密码
        String mobile = loginVo.getMobile();
        String password = loginVo.getPassword();

        //参数校验
        //判断密码是否为空
//        if(StringUtils.isEmpty(mobile)||StringUtils.isEmpty(password)){
//            return RespBean.error(RespBeanEnum.LOGIN_ERROR);
//        }
//        //校验手机号
//        if(!ValidatorUtil.isMobile(mobile)){
//            return RespBean.error(RespBeanEnum.MOBILE_ERROR);
//        }

        //根据手机号获取用户
        User user = userMapper.selectById(mobile);
        if(null==user){
//            return RespBean.error(RespBeanEnum.LOGIN_ERROR);
            throw new GlobalException(RespBeanEnum.LOGIN_ERROR);
        }
        //判断密码是否正确
        if(!MD5Util.fromPassToDBPass(password,user.getSalt()).equals(user.getPassword())){
//            return RespBean.error(RespBeanEnum.LOGIN_ERROR);
            throw new GlobalException(RespBeanEnum.LOGIN_ERROR);
        }

        //生成cookie
        String ticket = UUIDUtil.uuid();

        //方式一：保存session
//        request.getSession().setAttribute(ticket,user);

        //方式二：使用redis存储用户信息
        redisTemplate.opsForValue().set("user:"+ticket,user);

        //设置Cookie
        CookieUtil.setCookie(request,response,"userTicket",ticket);

        return RespBean.success(ticket);
    }

    /**
     * 功能描述：根据Cookie 获取用户信息
     *
     * @param userTicket
     * @param request
     * @param response
     * @return
     */
    @Override
    public User getUserByCookie(String userTicket, HttpServletRequest request, HttpServletResponse response) {
        if(StringUtils.isEmpty(userTicket)){
            return null;
        }

        //获取用户信息
        User user =(User) redisTemplate.opsForValue().get("user:" + userTicket);
//        if(user!=null){
//            //重新设置Cookie
//            CookieUtil.setCookie(request,response,"userTicket",userTicket);
//        }

        return user;
    }

    /**
     * 功能描述：更新密码
     *
     * 对象缓存：
     *    保证一致性：数据库和Redis数据一致性
     *    通过删除Redis缓存保证一致性
     */
    @Override
    public RespBean updatePassword(String userTicket, String password, HttpServletRequest request, HttpServletResponse response) {

        //获取用户信息
        User user = getUserByCookie(userTicket, request, response);

        if(user==null){
            throw new GlobalException(RespBeanEnum.MOBILE_NOT_EXIST);
        }
        //设置密码
        user.setPassword(MD5Util.inputPassToDBPass(password,user.getSalt()));
        //更新操作，更新成功则删除Redis缓存
        int result = userMapper.updateById(user);
        if(result==1){
            //删除Redis缓存
            redisTemplate.delete("user:"+userTicket);
            return RespBean.success();
        }
        //否则 返回失败信息
        return RespBean.error(RespBeanEnum.PASSWORD_UPDATE_FAIL);
    }
}
